<?php
/**
 * 云上绵州商品
 */

use app\config\Db;
use Core\Common\Common;
use Core\Result\Result;
use Core\Utils\Utils;
use GuzzleHttp\Client;


/**
 * 分类列表 TODO
 * @param
 * @return void
 */
function category($data)
{
    $category_pid = $data['category_pid'];
    $limit = 30;
    if(empty($category_pid) || $category_pid <=0){
        $category_pid = 0;
        $limit = 10;
    }
    $where = "`is_delete` = 0 and is_hide = 0 and category_pid =$category_pid";
    $order = "order by sort desc,create_time desc limit $limit";
    $field = 'category_id,category_pid,category_name,img_id';
    $db = new Db();
    $categoryInfo = $db->query("select $field from ysmz_shop_category where $where $order");
    if (strpos($field, 'img_id') !== false) {
        $fileId = array_column($categoryInfo, 'img_id');
        $fileId = implode(',', $fileId);
        $fileInfo = $db->query("select file_id,storage,`domain`,file_path from ysmz_file where file_id in($fileId)");
        foreach ($fileInfo as $k => $v) {
            $fileInfo[$k]['file_url'] = Common::fileUrl($v)."?_rand=".mt_rand(100,999);
        }
        $fileInfo = array_column($fileInfo, 'file_url', 'file_id');
    }
    foreach ($categoryInfo as $k => $v) {
        $categoryInfo[$k]['img_url'] = $fileInfo[$v['img_id']] ?? '';
    }
    //$categoryInfo = Common::list_to_tree($categoryInfo, 'category_id', 'category_pid');
    Result::Success($categoryInfo);
}

/**
 * @Apidoc\Title("商品列表")
 * @Apidoc\Param(ref="pagingParam")
 * @Apidoc\Param(ref="sortParam")
 */
function goodsList($data)
{
    $goods_type = $data['goods_type'];//1、上新，2精选好物，3热卖专区，4特价商品 5普通商品 6虚拟商品
    $category_id = $data['category_id'];
    $section_id = $data['section_id'];
    $name = $data['name'];
    $page = $data['page'];
    $limit = $data['limit'];
    if(($goods_type && !is_numeric($goods_type)) || ($category_id &&!is_numeric($category_id)) || ($section_id && !is_numeric($section_id)) || ($page && !is_numeric($page)) || ($limit && !is_numeric($limit))){
        Result::error("参数错误");
    }
    $where = " is_delete=0 and is_adopt=1 and is_top=1 and ys.status = 1";
    //if (empty($category_id) && empty($section_id) && empty($goods_type)) $where .= " and ysg.`category_id` in(1,2,3,4,5,6,7,8,9,10)";
    if ($category_id && $category_id != 0) $where .= " and ysg.`category_id`=$category_id";
    if ($section_id && $section_id != 0) $where .= " and ysg.`section_id`=$section_id";
    if ($name) $where .= " and `name` like '%$name%'";
    switch ($goods_type) {
        case 1://上新
            $where .= " and `is_news` = 1";
            $order = "order by sort desc,unreal_sales_volume desc,sales_volume desc,create_time desc";
            break;
        case 2://精选好物
            $where .= " and `is_rec` = 1";
            $order = "order by sort desc,sell_price asc,sales_volume desc,sort desc,create_time desc";
            break;
        case 3://热卖专区
            $where .= " and `is_hot` = 1";
            $order = "order by sort desc,sell_price asc,sales_volume desc,sort desc,create_time desc";
            break;
        case 4://特价商品
            $where .= " and `is_super` = 1";
            $order = "order by sort desc,sell_price asc,sales_volume desc,sort desc,create_time desc";
            break;
        case 5://普通商品
            $where .= " and `goods_type` = 1";
            $order = "order by sort desc,sell_price asc,sales_volume desc,sort desc,create_time desc";
            break;
        case 6://虚拟商品
            $where .= " and `goods_type` = 3";
            $order = "order by sort desc,sell_price asc,sales_volume desc,sort desc,create_time desc";
            break;
        default:
            $order = "order by sort desc,unreal_sales_volume desc,sales_volume desc,create_time desc";
            break;
    }
    $field = 'goods_id,ysg.category_id,ysg.shop_id,ysg.name,ysg.goods_type,ysg.title,old_price,sell_price,game_points,img_id,hits,sales_volume,unreal_sales_volume,create_time';
    $db = new Db();
    $goodsInfo = $db->query("select $field from ysmz_shop_goods as ysg inner join ysmz_shop as ys on ysg.shop_id = ys.shop_id where $where $order limit $page,$limit");
    $imgIds = implode(',', array_column($goodsInfo, 'img_id', 'img_id'));
    $categoryIds = implode(',', array_column($goodsInfo, 'category_id'));
    $fileInfo = [];
    if(!empty($imgIds)){
        $fileInfo = $db->query("select file_id,storage,`domain`,file_path from ysmz_file where file_id in($imgIds)");
    }
    foreach ($fileInfo as $k => $v) {
        $fileInfo[$k]['file_url'] = Common::fileUrl($v);
    }
    $fileInfo = array_column($fileInfo, 'file_url', 'file_id');
    $categoryInfo = [];
    if(!empty($categoryIds)){
        $categoryInfo = $db->query("select category_id,category_name from ysmz_shop_category where category_id in($categoryIds)");
    }
    $categoryInfo = array_column($categoryInfo, 'category_name', 'category_id');
    foreach ($goodsInfo as $k => $v) {
        $goodsInfo[$k]['img_url'] = $fileInfo[$v['img_id']] ?? '';
        $goodsInfo[$k]['category_name'] = $categoryInfo[$v['category_id']] ?? '(未分类)';
    }
    Result::success($goodsInfo);
}

/**
 * 商品信息 TODO
 * @param $data
 * @param $goods_id     商品ID
 * @return void
 */
function goodsInfo($data)
{
    $goods_id = $data['goods_id'];
    $db = new Db();
    $goodsInfo = $db->find("select *,(select sum(sku_stock) from `ysmz_shop_goods_sku` where `goods_id`=$goods_id and `is_delete`=0) as stock from `ysmz_shop_goods` where goods_id=$goods_id limit 1");
    if (!$goodsInfo) Result::error("商品信息不存在");
    if ($goodsInfo['is_adopt'] == 0) Result::error("商品未审核");
    if ($goodsInfo['is_top'] == 0) Result::error("商品已下架");
    if ($goodsInfo['is_delete'] == 1) Result::error("商品已删除");
    //$goodsInfo['sales_volume'] += $goodsInfo['unreal_sales_volume'];
    $fileIds = empty($goodsInfo['img_ids']) ? $goodsInfo['img_id'] : "{$goodsInfo['img_id']},{$goodsInfo['img_ids']}";
    $fileInfo = $db->query("select file_id,storage,`domain`,file_path from `ysmz_file` where `file_id` in($fileIds)");
    foreach ($fileInfo as $k => $v) {
        $fileInfo[$k]['file_url'] = Common::fileUrl($v);
    }
    $fileInfo = array_column($fileInfo, 'file_url', 'file_id');
    $goodsInfo['img_url'] = $fileInfo[$goodsInfo['img_id']] ?? '';
    $imgsInfo = [];
    foreach (explode(',', $goodsInfo['img_ids']) as $k => $v) {
        $imgsInfo[$k]['file_url'] = $fileInfo[$v];
    }
    $goodsInfo['imgs'] = [];
    if(!empty($imgsInfo[0]['file_url'])){
        $goodsInfo['imgs'] = $imgsInfo;
    }
    $categoryInfo = $db->query("select `category_id`,`category_name` from `ysmz_shop_category` where `category_id`={$goodsInfo['category_id']}");
    $goodsInfo['category_name'] = $categoryInfo['category_name'] ?? '(未分类)';

    $skuInfo = $db->query("select sku_id,goods_id,spec_info from `ysmz_shop_goods_sku` where `goods_id`=$goods_id and `is_delete`=0");
    $skuId = [];
    foreach ($skuInfo as $v) {
        $specArr = json_decode($v['spec_info']);
        foreach ($specArr as $kk => $vv) {
            $skuId[] = $kk;
            $skuId[] = $vv;
        }
    }
    $skuId = implode(',', array_unique($skuId));
    $specInfo = $db->query("select spec_id,spec_pid,name from `ysmz_shop_goods_spec` where spec_id in($skuId) and is_delete=0");
    $specInfo = Common::list_to_tree($specInfo, 'spec_id', 'spec_pid');
    $goodsInfo['spec'] = $specInfo;
    unset($goodsInfo['cost_price']);
    $goodsInfo["is_collect"] = false;
    $goodsInfo["shipping"] = shipping($goodsInfo);
    $user_id = Common::getUser_id($data);
    //查询是否用户收藏
    if($user_id){
        $collectInfo = $db->find("select `id` from `user_goods_collect` where `user_id` =$user_id and `g_id` = $goods_id");
        if(!empty($collectInfo)){
            $goodsInfo["is_collect"] = true;
        }
        $hostDb = new Db("host");
        $browseId = $hostDb->find("select `id` from `user_goods_browse` where `user_id` =$user_id and `g_id` = $goods_id")["id"];
        if(empty($browseId)){
            $BrowseSql = "INSERT INTO `user_goods_browse` (`user_id`, `g_id`) VALUES ($user_id,$goods_id)";
        }else{
            $time = time();
            $datetime = date('Y-m-d H:i:s', $time);
            $BrowseSql = "UPDATE `user_goods_browse` SET `create_date` = '$datetime' WHERE `id` = $browseId";
        }
        $hostDb->save($BrowseSql);
    }
    $shopInfo = $db->find("select `shop_id`,`shop_title`,`shop_logo`,`kefu_phone`,`kefu_weixin`,`cust_addr` from `ysmz_shop` where `shop_id` =$goodsInfo[shop_id]");
    $fileInfo = $db->find("select file_id,storage,`domain`,file_path from `ysmz_file` where `file_id` =$shopInfo[shop_logo]");
    $shopInfo['shop_logo'] = Common::fileUrl($fileInfo);
    //查询服务
    $serviceInfo = $db->find("select `name`,`icon` from `ysmz_shop_service` where `sid` =$goodsInfo[shop_id] and `status` = 1 limit 1");
    if(!empty($serviceInfo["name"])){
        $service = $serviceInfo["name"];
    }else{
        if(in_array($goodsInfo["section_id"],[2,3,5,9,10])){
            $service = "未核销可全额退款";
        }else{
            if($goodsInfo["category_id"] > 10){
                $categoryInfo = $db->find("select `category_pid` from `ysmz_shop_category` where `category_id` =$goodsInfo[category_id] limit 1");
            }
            if(in_array($goodsInfo["category_id"],[6,7,8,9,10]) || in_array($categoryInfo["category_pid"],[6,7,8,9,10])){
                $service = "支持7天无理由退货";
            }else{
                $service = "为了保证商品品质与每位顾客的权益，如非质量问题暂不支持退换，敬请理解。";
            }
        }
    }
    //查询评价
    $reviewsInfo = CommonComment($db, $goods_id, 0, 3);
    $res["goods"] = $goodsInfo;
    $res["shop"] = $shopInfo;
    $res["service"] = $service;
    $res["reviews"] = $reviewsInfo;
    Result::success($res);
}

/**
 * 商品SKU TODO
 * @param $data
 * @return void
 */
function skuSearch($data)
{
    $goods_id = $data['goods_id'];
    $spec_id = $data['spec_id'];
    $where = "gs.goods_id= $goods_id and gs.is_delete = 0";
    $spec_id = json_decode($spec_id,true);
    if (!empty($spec_id) && is_array($spec_id)) {
        foreach ($spec_id as $k => $v) {
            $where .= " and JSON_CONTAINS(gs.spec_info,JSON_OBJECT($k, $v))";
        }
    }
    $db = new Db();
    $goodsSkuInfo = $db->find("select sku_id,gs.goods_id,sku_code,sku_name,sku_img_id,sku_stock,sku_old_price,sku_sell_price,sku_game_points,g.goods_type,g.free_shipping ,g.fixed_shipping_type,g.shipping_method,g.fixed_shipping_type,g.fixed_shipping_fee from `ysmz_shop_goods_sku` as gs inner join `ysmz_shop_goods` as g on gs.goods_id=g.goods_id where $where");
    if (!$goodsSkuInfo) Result::error("商品SKU不存在");
    $fileInfo = $db->find("select file_id,storage,`domain`,file_path from `ysmz_file` where `file_id`={$goodsSkuInfo['sku_img_id']} limit 1");
    $goodsSkuInfo['sku_img_url'] = Common::fileUrl($fileInfo);
    $goodsSkuInfo['spec_name'] = '';
    if (!empty($spec_id) && is_array($spec_id)) {
        //$specId = implode(',', $spec_id);
        foreach ($spec_id as $k => $v) {
            $specId = $k.",".$v;
        }
        $specInfo = $db->query("select spec_id,name from `ysmz_shop_goods_spec` where `spec_id` in($specId)");
        $specInfo = implode(',', array_column($specInfo, 'name'));
        $goodsSkuInfo['spec_name'] = $specInfo;
    }
    Result::success($goodsSkuInfo);
}
/**
 * 商品所有评论 TODO
 * @param $data
 * @return void
 */
function goodsAllComments($data)
{
    $goods_id = $data['goods_id'];
    $page = $data['page'];
    $limit = $data['limit'];
    $db = new Db();
    $reviewsInfo = CommonComment($db, $goods_id, $page, $limit);
    Result::success($reviewsInfo);
}
/**
 * 商品收藏/取消收藏 TODO
 * @param $data
 * @return void
 */
function goodsCollect($data)
{
    $goods_id = $data['goods_id'];
    $user_id = Common::getUser_id($data);
    $db = new Db("host");
    $collectInfo = $db->find("select `id` from `user_goods_collect` where `user_id` =$user_id and `g_id` = $goods_id");
    if(!empty($collectInfo)){
        $deleSql = "delete from `user_goods_collect` where `user_id` =$user_id and `g_id` = $goods_id";
        $db->save($deleSql);
        $msg = -1;
    }else{
        $insetSql = "INSERT INTO `user_goods_collect` (`user_id`, `g_id`) VALUES ($user_id, $goods_id)";
        $db->save($insetSql);
        $msg = 1;
    }
    Result::success($msg);
}
/**
 * 查看评论通用 TODO
 * @param $db,$goods,$limit,$page
 * @return array
 */
function CommonComment($db,$goods_id,$page,$limit)
{
    $reviewsList = $db->query("select `star`,`comment`,`img_url`,`create_date`,`user_id` from `ysmz_goods_reviews` where `g_id` =$goods_id and `state` = 1 order by `create_date` desc limit $page,$limit");
    foreach ($reviewsList as $k=>$v){
        $userInfo = $db->find("select `nickname`,`avatar` from `user_info` where `user_id` = $v[user_id]");
        $reviewsList[$k]["nickname"] = Utils::yc_truename($userInfo["nickname"]);
        $reviewsList[$k]["avatar"] = $userInfo["avatar"];
    }
    $reviewsInfo["info"] = $reviewsList;
    $reviewsInfo["count"] = $db->find("select count(`id`) as count from `ysmz_goods_reviews` where `g_id` =$goods_id and `state` = 1")["count"];
    //好评率按4星以上计算
    $reviewsInfo["positiveRating"] = (100)."%";
    if($reviewsInfo["count"] >0){
        $starCount = $db->find("select count(`id`) as count from `ysmz_goods_reviews` where `g_id` =$goods_id and `state` = 1 and `star` >= 4")["count"];
        $reviewsInfo["positiveRating"] = ($starCount / $reviewsInfo["count"] * 100)."%";
    }
    return $reviewsInfo;
}
function shipping($goodsInfo)
{
    if($goodsInfo["free_shipping"] == 1){
        $shipping = "包邮";
    }else{
        if($goodsInfo["fixed_shipping_type"] == 1){
            $shipping = "运费：￥".$goodsInfo["fixed_shipping_fee"];//固定运费
        }else{
            $db = new Db();
            $shippingInfo = $db->find("select shipping_time,start_number,start_price,add_number,add_price,sti.free_price,sti.pricing_type from `ysmz_shipping_tpl` as st inner join `ysmz_shipping_tpl_info` as sti on st.shipping_tpl_id = sti.shipping_tpl_id where st.`shipping_tpl_id` = $goodsInfo[shipping_tpl_id]");
            $shipping = "基础运费：￥".$shippingInfo["start_price"].",满".$shippingInfo["free_price"]."包邮";//模版
        }
    }
    return $shipping;

}